import { Button, Form, Input, Modal, Pagination, Radio, Row, Select, Table } from 'antd'
import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import { SyncOutlined } from '@ant-design/icons'
import { profileAPI } from '@/apis'
import { genMaxId } from './utils'

export default () => {
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState(() => {
    return {
      keyword: null,
      page: 1,
      size: 10,
      total: 0,
      totalList: [],
      ruleList: [],
      list: [],
      visible: false,
      formData: {
        id: null,
        name: null, // 规则名称
        proportion: null, // 比重
        type: null, // 规则类型
        method: null, // 方式
        minCount: null, // 次数
        maxCount: null, // 最大次数
        score: null, // 得分
      },
    }
  })

  const loadData = async () => {
    setLoading(true)
    try {
      const totalList = await profileAPI.getEnterpriseProfileRule('/enterprise/profile/rule')
      data.totalList = totalList

      loadList()
    } catch (error) {
      console.log('error', error)
    }
    setLoading(false)
  }

  const loadRuleData = async () => {
    const ruleList = await profileAPI.getEnterpriseProfileContent('/enterprise/profile/content')
    data.ruleList = ruleList
    setData({
      ...data,
    })
  }

  const loadList = async () => {
    const totalList = data.totalList.filter((item) => {
      return data.keyword && item.name.indexOf(data.keyword) === -1 ? false : true
    })
    data.list = totalList.slice((data.page - 1) * data.size, data.page * data.size)
    data.total = totalList.length
    setData({
      ...data,
    })
  }

  const search = () => {
    data.page = 1
    loadList()
  }

  useEffect(() => {
    loadRuleData()
    loadData()
  }, [])

  const openDetailDialog = (row) => {
    let formData = {
      id: null,
      name: null, // 规则名称
      proportion: null, // 比重
      type: null, // 规则类型
      method: null, // 方式
      minCount: null, // 次数
      maxCount: null, // 最大次数
      score: null, // 得分
    }
    if (row) {
      formData = {
        id: 1,
        name: row.name, // 规则名称
        proportion: row.proportion, // 比重
        type: row.type, // 规则类型
        method: row.method, // 方式
        minCount: row.minCount, // 次数
        maxCount: row.maxCount, // 最大次数
        score: row.score, // 得分
      }
    }
    form.setFieldsValue(formData)
    setData({
      ...data,
      visible: true,
      formData,
    })
  }

  const openDelDialog = (row) => {
    Modal.confirm({
      title: '删除',
      content: '确定删除该条数据吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        const index = data.totalList.findIndex((r) => r.id === row.id)
        if (index !== -1) {
          data.totalList.splice(index, 1)
        }
        loadList()
      },
    })
  }

  const columns = [
    { title: 'id', width: '50px', dataIndex: 'id', key: 'id' },
    { title: '规则名称', dataIndex: 'name', key: 'name' },
    { title: '比重', width: '80px', key: 'proportion', render: (_, record) => `${record.proportion}%` },
    {
      title: '区间',
      key: 'minCount',
      render: (_, record) => {
        let str = ''
        if (record.method == 1) {
          str = '超过' + record.minCount
        } else if (record.method == 3) {
          str = '低于' + record.minCount
        } else if (record.method == 4) {
          str = record.minCount + '-' + record.maxCount
        } else {
          str = record.minCount
        }

        return str + (record.type === 1 ? '次' : '分')
      },
    },
    { title: '得分', key: 'score', render: (_, record) => `${record.score}分` },
    {
      title: '操作',
      width: '160px',
      key: 'op',
      render: (_, record) => (
        <>
          <Button size="small" color="default" type="link" onClick={() => openDetailDialog(record)}>
            编辑
          </Button>
          <Button size="small" color="default" type="link" onClick={() => openDelDialog(record)}>
            删除
          </Button>
        </>
      ),
    },
  ]

  const handleChangeSize = (page, pageSize) => {
    ;(data.page = page), (data.size = pageSize)
    setData({
      ...data,
      size: pageSize,
      page: page,
    })
    loadList()
  }

  const onChangeKeyword = (e) => {
    setData({
      ...data,
      keyword: e.target.value,
    })
  }

  const handleChangeVisible = (visible) => {
    setData({
      ...data,
      visible,
    })
  }

  const [form] = Form.useForm()
  const handleSubmit = async () => {
    await form.validateFields()
    const formData = form.getFieldsValue()
    if (data.formData.id) {
      const row = data.totalList.find((r) => r.id === data.formData.id)
      row.method = formData.method
      row.minCount = formData.minCount
      row.maxCount = formData.maxCount
      row.score = formData.score
    } else {
      const rule = data.ruleList.find((r) => r.id === formData.name)
      const row = {
        id: genMaxId(data.totalList),
        name: rule.name,
        proportion: rule.proportion,
        type: rule.type,
        method: formData.method,
        minCount: formData.minCount,
        maxCount: formData.maxCount,
        score: formData.score,
      }
      data.totalList.push(row)
    }
    profileAPI.saveEnterpriseProfileRule('/enterprise/profile/rule', data.totalList)
    data.visible = false
    loadList()
  }

  return (
    <div className={styles.page}>
      <div className={styles.header}>
        <div className={styles.title}>园区画像评估规则设置</div>
        <div className={styles.search}>
          <Input style={{ marginLeft: 10 }} value={data.keyword} onChange={onChangeKeyword}></Input>
          <Button type="primary" icon={<SyncOutlined />} style={{ marginLeft: 10 }} onClick={search}>
            查询
          </Button>
          <Button
            type="primary"
            style={{ marginLeft: 10 }}
            onClick={() => {
              openDetailDialog(null)
            }}
          >
            添加
          </Button>
        </div>
      </div>
      <div className={styles.table}>
        <Table loading={loading} columns={columns} dataSource={data.list} pagination={false} rowKey="id" />
      </div>
      <div className={styles.paging}>
        <Pagination
          current={data.page}
          total={data.total}
          pageSize={data.size}
          showSizeChanger
          onChange={handleChangeSize}
        />
      </div>
      <Modal
        title={`园区画像评估规则-${data.formData.id ? '编辑' : '添加等级'}`}
        open={data.visible}
        onCancel={() => handleChangeVisible(false)}
        onOk={() => handleSubmit()}
        okText="保存"
        cancelText="取消"
        footer={(_, { OkBtn, CancelBtn }) => (
          <>
            <CancelBtn />
            <OkBtn />
          </>
        )}
      >
        <Form form={form} labelCol={{ span: 6 }} style={{ maxWidth: 600, padding: 20 }} labelAlign="right">
          <Form.Item label="规则名称" required name="name" rules={[{ required: true, message: '请选择规则名称' }]}>
            {data.formData.id ? (
              data.formData.name
            ) : (
              <Select
                style={{ width: 300 }}
                onChange={(value) => {
                  let proportion = null
                  let type = null
                  if (value) {
                    const row = data.ruleList.find((row) => row.id === value)
                    proportion = row.proportion
                    type = row.type
                  }
                  form.setFieldValue('proportion', proportion)
                  form.setFieldValue('type', type)
                }}
              >
                {data.ruleList.map((row) => {
                  return <Select.Option value={row.id}>{row.name}</Select.Option>
                })}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="比重" shouldUpdate>
            {({ getFieldValue }) => {
              const proportion = getFieldValue('proportion')
              return proportion ? proportion + '%' : ''
            }}
          </Form.Item>
          <Form.Item label="类型" shouldUpdate>
            {({ getFieldValue }) => {
              const type = getFieldValue('type')
              return type ? ['-', '次', '分'][type] + '数' : ''
            }}
          </Form.Item>
          <Form.Item label="方式" name="method" required rules={[{ required: true, message: '请选择方式' }]}>
            <Radio.Group>
              <Radio value={1}>大于</Radio>
              <Radio value={2}>等于</Radio>
              <Radio value={3}>小于</Radio>
              <Radio value={4}>区间</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="次数" required shouldUpdate>
            {({ getFieldValue }) => {
              const method = getFieldValue('method')
              if (method !== 4) {
                return (
                  <Form.Item
                    name="minCount"
                    noStyle
                    rules={[
                      () => ({
                        validator(_, value) {
                          return value ? Promise.resolve() : Promise.reject(new Error('请填写'))
                        },
                      }),
                    ]}
                  >
                    <Input style={{ width: 130 }} type="number" min={0} placeholder="请填写数字"></Input>
                  </Form.Item>
                )
              } else {
                return (
                  <>
                    <Form.Item
                      name="minCount"
                      noStyle
                      rules={[
                        () => ({
                          validator(_, value) {
                            return value ? Promise.resolve() : Promise.reject(new Error('请填写'))
                          },
                        }),
                      ]}
                    >
                      <Input style={{ width: 130 }} type="number" min={0} placeholder="请填写数字"></Input>
                    </Form.Item>
                    <span style={{ margin: '0 10px' }}>至</span>
                    <Form.Item
                      name="maxCount"
                      noStyle
                      rules={[
                        () => ({
                          validator(_, value) {
                            return value ? Promise.resolve() : Promise.reject(new Error('请填写'))
                          },
                        }),
                      ]}
                    >
                      <Input style={{ width: 130 }} type="number" min={0} placeholder="请填写数字"></Input>
                    </Form.Item>
                    <span style={{ marginLeft: '10px' }}>{['-', '次', '分'][data.formData.type]}</span>
                  </>
                )
              }
            }}
          </Form.Item>
          <Form.Item label="得分" name="score" required rules={[{ required: true, message: '请输入得分' }]}>
            <Input style={{ width: 200 }} min={0} type="number"></Input>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
